package com.kotiln.lgc.lib_network

import com.kotiln.lgc.lib_network.http.ServiceCreator
import com.kotiln.lgc.lib_network.impl.HttpImplService
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

/**
 *@fileName HttpManager
 *@date2021/1/25  15:32
 *@author HttpManager$
 *@describe TODO
 *@desc 对外的网络管理类
 */
object HttpManager {

    //---------------------------------Jetpack------------------------------------------------------
    private val httpImplService: HttpImplService = ServiceCreator.create<HttpImplService>()
    //查询天气
//    suspend fun queryWeather(city:String)= httpImplService.getWeather(city,HttpKey.WEATHER_KEY).await()

    private suspend fun <T> Call<T>.await(): T {
        return suspendCoroutine { continuation ->
            enqueue(object : Callback<T> {
                override fun onResponse(call: Call<T>, response: Response<T>) {
                    val body = response.body()
                    if (body != null) continuation.resume(body)
                    else continuation.resumeWithException(RuntimeException("response body is null"))
                }

                override fun onFailure(call: Call<T>, t: Throwable) {
                    continuation.resumeWithException(t)
                }

            })
        }
    }


    //-----------------------------------普通Retrofit------------------------------------------------------------

    //创建客户端
    //private fun getClient():OkHttpClient{
    //return OkHttpClient.Builder().addInterceptor(HttpInterceptor()).build()
    //}

    //天气对象
    //private val retrofitWeather:Retrofit by lazy {
    // Retrofit.Builder().client(getClient()).baseUrl(HttpUrl.WEATHTER_BASE_URL)
    // .addConverterFactory(GsonConverterFactory.create()).build()
    //}

    //AppId接口对象
    private val apiService: HttpImplService by lazy {
        ServiceCreator.create<HttpImplService>()
    }

    //appId
    fun queryAppId(mach: String): Call<ResponseBody> {
        return apiService.getAppIdInfo(mach)
    }
    //kind
    fun getKindInd(body: RequestBody):Call<ResponseBody>{
        return apiService.getKindInfo(body)
    }
    //百度
    fun queryBaiduInfo():Call<ResponseBody>{
        return apiService.getBaiduInfo()
    }
}


